package com.qf.lanzhou.blog.api.controller;

import com.alibaba.fastjson.JSON;
import com.qf.lanzhou.blog.api.pojo.entity.User;
import com.qf.lanzhou.blog.api.service.ShowUsersService;
import com.qf.lanzhou.blog.api.service.impl.ShowUsersServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author jian  展示用户信息并修改
 * @Date 2020/12/17 16:00
 * @JDK 1.8
 * @Version 1.0
 */
@WebServlet("/showuser.do")
public class ShowUsersServlet extends BaseServletPost{
    private ShowUsersService showUsersService=new ShowUsersServiceimpl();


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决请求的乱码
        req.setCharacterEncoding("utf-8");
        //解决响应乱码
        resp.setContentType("text/html;charset=utf-8");

        //获取参数
        User user1 = (User) req.getSession().getAttribute("user");
        Long id = user1.getId();
        //转为string类型
        String userId = id + "";
        String userName = req.getParameter("userName");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex");
        String createTime = req.getParameter("createTime");

        //封装参数
        User user = new User();
        user.setId(id);
        user.setUserName(userName);
        user.setPhone(phone);
        user.setEmail(email);
        user.setAge(Integer.parseInt(age));
        user.setSex(sex);
        //user.setCreateTime(createTime);
       // user.setCreateTimeStr(user.getCreateTime());

        //从数据库查询所有信息,并把集合返回前端
        List<User> list=showUsersService.checkUser(id);
        for (User user2:list) {
            user2.setCreateTime(user2.getCreateTime());
        }
        successResultWrite(list,resp);
//        String json = JSON.toJSONString(list);
//        resp.getWriter().write(json);


        //修改用户信息
        int i=showUsersService.update(user);
        if(i==1){
            resp.getWriter().write("修改成功");
        }else {
            resp.getWriter().write("修改失败,请重新修改");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
